﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using OpenQuarters.WebQuarters.Utils;
using System.Web.UI;
using System.IO;
using System.Text;

namespace OpenQuarters.WebQuarters.Core
{
    [Newtonsoft.Json.JsonObject(Newtonsoft.Json.MemberSerialization.OptIn)]
    [Serializable]
    public abstract class Module : System.Web.Mvc.ViewUserControl
    {
        private string moduleName = "New Module Name";

        public string ModuleName
        {
            get { return moduleName; }
            set { moduleName = value; }
        }

        private string moduleDescription = "";

        public string ModuleDescription
        {
            get { return moduleDescription; }
            set { moduleDescription = value; }
        }

        private string moduleId = "";

        [Newtonsoft.Json.JsonProperty]
        public string ModuleId
        {
            get
            {
                if (moduleId.Length == 0)
                {
                    moduleId = Utils.GeneralUtils.GetGuid();
                }
                return moduleId;
            }
            set { moduleId = value; }
        }

        public Module()
        {
            Initialise();
        }

        public virtual void Initialise()
        {
        }

        public ModuleDefinition ToDefinition()
        {
            return new ModuleDefinition(this);
        }

        public virtual string GetJQueryEditorName()
        {
            return "cmsModuleEditor";
        }

        public static List<ModuleInfo> GetModules()
        {
            var modules = new List<ModuleInfo>();

            foreach (var type in GeneralUtils.GetSubclassesOf(typeof(Module), true))
            {
                if (!type.IsAbstract)
                {
                    bool showModule = true;

                    var attrs = type.GetCustomAttributes(typeof(ModuleConfigurationAttribute), false).ToList();
                    if (attrs.Count > 0)
                    {
                        var attr = (ModuleConfigurationAttribute)attrs[0];
                        if (attr.Hidden)
                        {
                            showModule = false;
                        }
                    }

                    if (showModule)
                    {
                        var moduleInstance = (Module)Activator.CreateInstance(type);
                        modules.Add(new ModuleInfo()
                        {
                            Name = moduleInstance.ModuleName,
                            Description = moduleInstance.ModuleDescription,
                            FullName = type.FullName
                        });
                    }
                }
            }

            return modules.OrderBy(m => m.Name).ToList();
        }
    }
}
